<template>
	<div>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText" @tap="toBack">返回</block>
			<block slot="content">表单</block>
		</cu-custom>
		<view class="cu-form-group margin-top">
			<view class="title">起始地点</view>
			<input name="start" id="start" v-model="startName" @input="searchStartLocation"></input>
				<view v-if="startSuggestions.length" class="suggestions">
				<view v-for="(item, index) in startSuggestions" :key="index" @click="selectStartSuggestion(item)">

			    </view>
			</view>
		</view>
		<view class="cu-form-group margin-top">
			<view class="title">结束地点</view>
			<input name="end" id="end" v-model="endName" @input="searchEndLocation"></input>
			 <view v-if="endSuggestions.length" class="suggestions">
			    <view v-for="(item, index) in endSuggestions" :key="index" @click="selectEndSuggestion(item)">	
			    </view>
			</view>
		</view>
			<p>当前位置: {{ currentLocation }}</p>
		    <p>起点经纬度: {{ startLocation }}</p>
		    <p>终点经纬度: {{ endLocation }}</p>
		    <p>两地相距约：{{ distance }}</p><br>
		<button @click="goView">查询</button>
		<div id="container"></div>
	</div>
</template>
<script>
	import AMapLoader from '@amap/amap-jsapi-loader'
	
	export default {
	  name: 'AMapView',
	  data() {
	    return {
				  map: null,
			      startName: '',
			      endName: '',
			      distance: '',
			      startLocation: '',
			      endLocation: '',
			      currentLocation: '',
			      autoCompleteStart: null,
			      autoCompleteEnd: null,
			      startSuggestions: [],
			      endSuggestions: [],
			      driving: null
	    }
	  },
	  mounted() {
	    window._AMapSecurityConfig = {
	      securityJsCode: '25b26801223ff8fc99496fe1224eb224' // 申请key对应的秘钥
	    }
	    // DOM初始化完成进行地图初始化
	    this.initMap()
		this.getCurrentLocation()
	  },
	  methods: {
		  toBack() {
		        uni.redirectTo({
						url: "/pages/index/index"
		        })
		      },
	     async goView() {
	          if (!this.startName || !this.endName) {
	            return;
	          }
			
			// 创建 driving 实例
			if (this.driving) {
			  this.driving.clear(); // 清除之前的路线
			} else {
			  this.driving = new AMap.Driving({
			    map: this.map,
			    policy: AMap.DrivingPolicy.LEAST_TIME
			  })
			}
	      // 定义路径上的点
      const points = [
        { keyword: this.startName, city: '北京' },
        { keyword: this.endName, city: '北京' }
      ]
	
	       // 路径规划
      this.driving.search(points, (status, result) => {
        if (status === 'complete') {
          console.log('路径规划成功:', result);

          // 计算距离
          this.distance = this.formatDistance(result.routes[0].distance);

          // 计算预计所需时间
          const duration = this.formatDuration(result.routes[0].duration);
          if (typeof duration === 'number' && !isNaN(duration)) {
            this.duration = this.formatDuration(duration);
            console.log('预计时间:', this.duration)
          } else {
            console.log(this.duration = '无法获取时间');
          }
        } else {
          console.error('路径规划失败:', status, result);
          this.distance = '无法获取距离';
          this.duration = '无法获取时间';
        }
      })
	},
	    initMap() {
	      AMapLoader.load({
	        key: 'acf05601e0cf6e2d6d44866227598eac', // 申请好的Web端开发者Key，首次调用 load 时必填
	        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
	        plugins: ['AMap.ToolBar', 'AMap.Driving', 'AMap.AutoComplete', 'AMap.Geocoder'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
	      }).then(AMap => {
	        this.map = new AMap.Map('container', { // 设置地图容器id
	          viewMode: '3D', // 是否为3D地图模式
	          zoom: 10, // 初始化地图级别
	          center: [116.39, 39.9] // 初始化地图中心点位置
	        })
			const autoOptions = {
			  city: '北京',
			  input: 'start'
			}	
			this.autoCompleteStart = new AMap.AutoComplete(autoOptions)
			this.autoCompleteStart.on('select', this.handleStartSelect)
				
	        
	        const autoOptions2 = {
	          // city 限定城市，默认全国
	          city: '北京',
	          input: 'end'
	        }
	        // 实例化AutoComplete
	        this.autoCompleteEnd = new AMap.AutoComplete(autoOptions2)
        this.autoCompleteEnd.on('select', this.handleEndSelect)
	      }).catch(e => {
	        console.log(e)
	      })
	    }, 
	searchStartLocation() {
      this.autoCompleteStart.search(this.startName, (status, result) => {
        if (status === 'complete' && result.tips) {
          this.startSuggestions = result.tips
        }
      })
    },
    searchEndLocation() {
      this.autoCompleteEnd.search(this.endName, (status, result) => {
        if (status === 'complete' && result.tips) {
          this.endSuggestions = result.tips
        }
      })
    },
    selectStartSuggestion(item) {
      this.startName = item.name;
      this.startLocation = `${item.location.lat}, ${item.location.lng}`;
      this.startSuggestions = [];
    },
    selectEndSuggestion(item) {
      this.endName = item.name;
      this.endLocation = `${item.location.lat}, ${item.location.lng}`;
      this.endSuggestions = [];
    },
    handleStartSelect(event) {
      const { name, location } = event.poi;
      this.startName = name;
      this.startLocation = `${location.lat}, ${location.lng}`;
      this.startSuggestions = [];
    },
    handleEndSelect(event) {
      const { name, location } = event.poi;
      this.endName = name;
      this.endLocation = `${location.lat}, ${location.lng}`;
      this.endSuggestions = [];
    },
    getCurrentLocation() {
          AMapLoader.load({
            key: 'acf05601e0cf6e2d6d44866227598eac',
            version: '2.0',
            plugins: ['AMap.Geolocation']
          }).then(AMap => {
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true,
              timeout: 10000,
              buttonOffset: new AMap.Pixel(10, 20),
              zoomToAccuracy: true
            })
    
            this.map.addControl(geolocation)
			console.log(geolocation)
            geolocation.getCurrentPosition((status, result) => {
				console.log(status + result)
              if (status === 'complete') {
                const { position } = result
                this.currentLocation = `${position.lat}, ${position.lng}`
              } else {
                console.error('获取当前位置失败:', status)
              }
            })
          }).catch(e => {
            console.log(e)
          })
        },
    formatDistance(distance) {
      return `${distance / 1000} 公里`;
    },
    formatDuration(duration) {
      const minutes = Math.floor(duration / 60);
      const seconds = duration % 60;
      return `${minutes} 分 ${seconds} 秒`;
    }
  },
	}
</script>

<style>
#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 800px;
}
.suggestions {
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-y: auto;
  background: #fff;
}
.suggestions view {
  padding: 10px;
  cursor: pointer;
}
.suggestions view:hover {
  background: #f5f5f5;
}
</style>
